package com.ruoyi.mobile.project.sms.service;

import com.ruoyi.db.sms.domain.SmsCoupon;
import com.ruoyi.db.sms.domain.SmsCouponUser;
import com.ruoyi.mobile.project.utils.CouponConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class WxCouponAssignService
{

    @Autowired
    private WxSmsCouponUserService couponUserService;

    @Autowired
    private WxSmsCouponService couponService;

    /**
     * 分发注册优惠券
     *
     * @param userId
     * @return
     */
    public void assignForRegister(Long userId)
    {
        List<SmsCoupon> couponList = couponService.queryRegister();
        for (SmsCoupon coupon : couponList)
        {
            Long couponId = coupon.getId();

            Integer count = couponUserService.countUserAndCoupon(userId, couponId);
            if (count > 0)
            {
                continue;
            }

            Integer limitGet = coupon.getLimitGet();
            while (limitGet > 0)
            {
                SmsCouponUser couponUser = new SmsCouponUser();
                couponUser.setCouponId(couponId);
                couponUser.setUserId(userId);
                Integer timeType = coupon.getTimeType();
                if (timeType.equals(CouponConstant.TIME_TYPE_TIME))
                {
                    couponUser.setStartTime(coupon.getStartTime());
                    couponUser.setEndTime(coupon.getEndTime());
                }
                else
                {
                    LocalDateTime now = LocalDateTime.now();
                    couponUser.setStartTime(now);
                    couponUser.setEndTime(now.plusDays(coupon.getDays()));
                }
                couponUserService.add(couponUser);

                limitGet--;
            }
        }

    }

}
